package com.rongxue.service.Impl;

import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.rzzf.P2PXmlUtils;
import com.rongxue.service.CashInAndOutService;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.service.utils.RecordsUtils;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.ExceptionUtils;
import com.alibaba.fastjson.JSONObject;
import com.rongxue.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.Test;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service
@Transactional
public class CashInAndOutServiceImpl implements CashInAndOutService {

    private static final Logger LOG = LoggerFactory.getLogger(CashInAndOutServiceImpl.class);
    @Autowired
    private SUserMoneyRecordsMapper userMoneyRecordsMapper;
    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SUserWalletRecordsMapper userWalletRecordsMapper;
    @Autowired
    private SUserAccountMapper userAccountMapper;
    @Autowired
    private SBankTypeMapper bankTypeMapper;
    @Autowired
    private SUserCashCouponMapper userCashCouponMapper;
    @Autowired
    private SInvestmentDetailMapper investmentDetailMapper;
    @Autowired
    private RecordsUtils recordsUtils;
    @Autowired
    private STelephonerateRechargeMapper sTelephonerateRechargeMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(CashInAndOutService.class);


    //测试环境
////    public static String MCHNT_CD = "0002900F0096235";//商户代码快捷
//
//    public static String MCHNT_CD = "0001000F0040992";//商户代码手机银行
//
//    public static String KEY = "vau6p7ldawpezyaugc0kopdrrwm4gkpu";//手机支付秘钥
//
//    public static String PAGE_NOTIFY_URL = "http://api.jsrongdai.cn:8080/jishangtest/";//商户回调地址
//
//    public static String P2P_SEND_MSG_URL = "http://www-1.fuiou.com:18670/mobile_pay/";//认证支付url
//
//    public static String APP_MCHNT_CD = "0002900F0096235";//APP商户代码
//
//    public static String APP_KEY = "5old71wihg2tqjug9kkpxnhx9hiujoqj";//快捷秘钥
//
//    private static String mchnt_key = "vau6p7ldawpezyaugc0kopdrrwm4gkpu"; //富有秘钥
//
//    public static String ADMIN_URL ="http://testadmin.jsrongdai.cn";//后台地址



    //正式环境
    public static String MCHNT_CD = "0003310F1905188";//商户代码

    public static String KEY = "aavwo5191kzbv31mjr1xbminc2ejrqh8" ;

    public static String APP_KEY = "aavwo5191kzbv31mjr1xbminc2ejrqh8";//快捷支付秘钥

    public static String PAGE_NOTIFY_URL = "http://api.zhaobeixxkj.com:8080/fudelong/";//商户回调地址

    public static String P2P_SEND_MSG_URL = "https://mpay.fuiou.com:16128/";//认证支付url

    public static String APP_MCHNT_CD = "0003310F1905188";//APP商户代码

    public static  String mobile_key = "hm0wc6doikbo2ntdesz5g49hu82adpnl";//手机银行秘钥

    private static String mchnt_key = "aavwo5191kzbv31mjr1xbminc2ejrqh8"; //富有秘钥

    public static String ADMIN_URL ="http://admin.zhaobeixxkj.com/";

////
    public static ConcurrentHashMap<String, Long> map = new ConcurrentHashMap();

    //充值
    @Override
    public ObjectResult recharge(XMLBean xmlBean) {

        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser user = userMapper.selectUserInfoById(Long.parseLong(userId));
        if (user == null) {
            return ObjectResult.build("0", "用户信息有误");
        }
        if (1 != user.getCardNoAuth()) {
            return ObjectResult.build("0", "请先进行实名认证");
        }

        Long user_id = user.getId();
        String rechargeNo = new P2PMessageUtils().getRechargeNo("R");

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank == null){
            return ObjectResult.build("0", "银行卡信息错误");
        }

        //充值限额
        BigDecimal money = new BigDecimal(xmlBean.getMoney());
        BigDecimal quota = new BigDecimal(100);
//        if (money.compareTo(quota) < 0 ){
//            return ObjectResult.build("0", "充值金额不能低于"+quota+"元");
//        }

        ObjectResult insertWalletRecordsResult = recordsUtils.insertWalletRecords(user_id, 1, new BigDecimal(xmlBean.getMoney()), rechargeNo,
                "用户充值", xmlBean.getDevice_type(), 2, sUserBank.getId());

        if (insertWalletRecordsResult != null){
            return insertWalletRecordsResult;
        }


        ///返回结果
        ResultBean resultBean = new ResultBean();
        SUserBank banks = userBankMapper.selectUserBankInfoByUserId(userId);
        UserInfo userInfo = new UserInfo();
        resultBean.setRecharge_on(rechargeNo);
        userInfo.setReal_name(user.getRealName());
        userInfo.setReal_name_auth(user.getRealNameAuth());
        userInfo.setCard_no(user.getCardNo());
        userInfo.setCard_no_auth(user.getCardNoAuth());
        userInfo.setMobile(user.getMobile());
        userInfo.setType(user.getType());
        userInfo.setLevel(user.getLevel());
        userInfo.setStatus(user.getStatus());
        userInfo.setBank_card_no(banks.getBankCardNo());
        userInfo.setBank_code(banks.getBankCode());
        SUserAccount sUserAccount = userAccountMapper.selectAccountAbleWaitInterestByUserId(user.getId());
        userInfo.setAccount_able(sUserAccount.getAccount_able());
        userInfo.setWait_interest(sUserAccount.getWait_interest());
        resultBean.setUserInfo(userInfo);
        if(xmlBean.getType()!=null&&xmlBean.getType()==2){
            resultBean.setUrl(PAGE_NOTIFY_URL + "tender/bankRechargeNotify");
        }else {
            resultBean.setUrl(PAGE_NOTIFY_URL + "tender/rechargeNotify");
        }

        return ObjectResult.build("1", "交易成功", resultBean);

    }

    //提现
    @Override
    public ObjectResult withdrawDeposit(XMLBean xmlBean) {

        long time = System.currentTimeMillis();
        Long oldTime = map.put(xmlBean.getToken(), time);

        if (oldTime != null){
            if (time - oldTime < 3000){
                return ObjectResult.build("0", "请勿重复提交");
            }
        }

        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser user = userMapper.selectUserInfoById(Long.parseLong(userId));
        if (user == null) {
            return ObjectResult.build("0", "用户信息有误");
        }
        if (1 != user.getCardNoAuth()) {
            return ObjectResult.build("0", "请先进行实名认证");
        }

        //提现限额
        BigDecimal money = new BigDecimal(xmlBean.getMoney());
        BigDecimal quota = new BigDecimal(2);
        if (money.compareTo(quota) < 0 ){
            return ObjectResult.build("0", "提现金额不能低于"+quota+"元");
        }

        //提现必须小于账户余额
        SUserAccount userAccount = this.userAccountMapper.selectUserAccountByUserId(user.getId());
        java.math.BigDecimal accountAble = userAccount.getAccount_able();
        if (accountAble.compareTo(money) < 0) {
            return com.rongxue.pojo.ObjectResult.build("0", "提现金额超过账户余额！");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank == null){
            return ObjectResult.build("0", "银行卡信息错误");
        }

        Long user_id = user.getId();
        String rechargeNo = new P2PMessageUtils().getRechargeNo("W");
        BigDecimal transAmount = new BigDecimal(0.00).subtract(money);

        //添加wallet成功记录
        recordsUtils.insertWalletRecords(user_id, 2, transAmount, rechargeNo, "用户提现", xmlBean.getDevice_type(), 3, sUserBank.getId());

        //添加成功记录
        ObjectResult saveCashAndOutRecordsResult = recordsUtils.saveCashAndOutRecords(user_id, transAmount, "用户提现", 2, rechargeNo , 3);
        if (saveCashAndOutRecordsResult != null){
            return saveCashAndOutRecordsResult;
        }
        //更改账户余额
        ObjectResult updateAccountAbleResult = recordsUtils.updateAccountAble(user_id, transAmount);
        if (updateAccountAbleResult != null){
            return updateAccountAbleResult;
        }

//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("mobile", user.getMobile());
//        hashMap.put("tpl_id", "92424");
//        hashMap.put("key", MobileCodeServiceImpl.SMS_KEY);
//        hashMap.put("tpl_value", "#name#="+user.getRealName()+"&#time#="+DateUtil.formatDateTime()+"&#money#="+money);

        return ObjectResult.build("1", "提现成功");
    }


    //充值回调
    @Override
    public ObjectResult verificationrechargeNotify(String type, String version, String responsecode, String responsemsg, String mchntcd,
                                                   String mchntorderid, String orderid, String amt, String bankcard, String sign) {

        //验签
        ObjectResult objectResult = new P2PMessageUtils().verificationNotifySign(type, version, responsecode,responsemsg, mchntcd, mchntorderid, orderid, amt, bankcard, sign);
        if (objectResult.getCode().equals("1")) {

            SUserWalletRecords sUserWalletRecords = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(mchntorderid);
            //返回数据验证
            if (sUserWalletRecords != null) {
                if (version.equals("2.0") && type.equals("02") && (mchntcd.equals(APP_MCHNT_CD))
                        && sUserWalletRecords.getRecharge_no().equals(mchntorderid)
                        && new BigDecimal(amt).compareTo(sUserWalletRecords.getValue().multiply(BigDecimal.valueOf(100))) == 0) {

                    //防止返回重复成功回调,重复添加记录
                    SUserWalletRecords sUserWalletRecordsResult = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(mchntorderid);
                    if (sUserWalletRecordsResult.getPayStatus() == 2) {
                        return ObjectResult.build("0", "重复记录");
                    }

                    //验签通过,更改账户余额,修改wallet成功,添加成功记录
                    try {
                        //保存返回码
                        Long userId = sUserWalletRecords.getUser_id();
                        BigDecimal value = sUserWalletRecords.getValue();

                        recordsUtils.saveCodeByTradeNo(sUserWalletRecordsResult.getRecharge_no(), responsecode+responsemsg);

                        SUserMoneyRecords moneyRecords = new SUserMoneyRecords();
                        moneyRecords.setUserId(userId);
                        moneyRecords.setValue(value);
                        moneyRecords.setDescr("用户充值");
                        moneyRecords.setType(108);
                        moneyRecords.setStatus(1);
                        moneyRecords.setAddTime(new Date());
                        userMoneyRecordsMapper.insert(moneyRecords);


                        recordsUtils.updateAccountAble(userId, value);
                        //修改充值提现记录表 设置为支付或者提现成功
                        userWalletRecordsMapper.updateStatusByRefnumber("2", sUserWalletRecords.getRecharge_no());

                        //设置银行卡已支付
                        SUserBank userBank = new SUserBank();
                        userBank.setUserId(sUserWalletRecordsResult.getUser_id());
                        userBank.setModifyTime(new Date());
                        userBank.setHasPaySuccess(2);
                        userBankMapper.updateByUserId(userBank);

                        SUser resultUser = userMapper.selectUserInfoById(userId);
                        //发送短信验证码

//                        HashMap<String, String> hashMap = new HashMap<>();
//                        hashMap.put("mobile", resultUser.getMobile());
//                        hashMap.put("tpl_id", "92420");
//                        hashMap.put("key", MobileCodeServiceImpl.SMS_KEY);
//                        hashMap.put("tpl_value", "#name#="+resultUser.getRealName()+"&#time#="+DateUtil.formatDateTime()+"&#money#="+value);
//                        ObjectResult objectResult2 = HttpClientUtil.verificationOfBankCard(MobileCodeServiceImpl.SMS_URL, hashMap);

                        return ObjectResult.build("1", "交易成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                    }


                } else {
                    return ObjectResult.build("0", "验签失败0x08");
                }

            }else {
                return ObjectResult.build("0", "不存在的充值记录");
            }

        }else {
            return objectResult;
        }

    }

    @Override
    public ObjectResult bankRechargeNotify(String fy_ssn, String mchnt_cd, String order_amt, String order_date, String order_id, String order_st, String order_pay_code, String order_pay_error, String resv1, String md5) {

        long time = System.currentTimeMillis();
        Long oldTime = map.put(order_id, time);

        if (oldTime != null){
            if (time - oldTime < 3000){
                return ObjectResult.build("0", "请勿重复提交");
            }
        }

        //验签
        ObjectResult objectResult = new P2PMessageUtils().bankRechargeNotify(fy_ssn, mchnt_cd, order_amt, order_date, order_id, order_st, order_pay_code, order_pay_error, resv1, md5);
        if (objectResult.getCode().equals("1")) {

            SUserWalletRecords sUserWalletRecords = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(order_id);
            //返回数据验证
            if (sUserWalletRecords != null) {
                if (mchnt_cd.equals(APP_MCHNT_CD)
                        && sUserWalletRecords.getRecharge_no().equals(order_id)
                        && new BigDecimal(order_amt).compareTo(sUserWalletRecords.getValue().multiply(BigDecimal.valueOf(100))) == 0) {

                    //防止返回重复成功回调,重复添加记录
                    SUserWalletRecords sUserWalletRecordsResult = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(order_id);
                    if (sUserWalletRecordsResult.getPayStatus() == 2) {
                        return ObjectResult.build("0", "重复记录");
                    }

                    //验签通过,更改账户余额,修改wallet成功,添加成功记录
                    try {
                        //保存返回码
                        Long userId = sUserWalletRecords.getUser_id();
                        BigDecimal value = sUserWalletRecords.getValue();

                        recordsUtils.saveCodeByTradeNo(sUserWalletRecordsResult.getRecharge_no(), order_pay_code + order_pay_error);

                        SUserMoneyRecords moneyRecords = new SUserMoneyRecords();
                        moneyRecords.setUserId(userId);
                        moneyRecords.setValue(value);
                        moneyRecords.setDescr("用户充值");
                        moneyRecords.setType(108);
                        moneyRecords.setStatus(1);
                        moneyRecords.setAddTime(new Date());
                        userMoneyRecordsMapper.insert(moneyRecords);


                        recordsUtils.updateAccountAble(userId, value);
                        //修改充值提现记录表 设置为支付或者提现成功
                        userWalletRecordsMapper.updateStatusByRefnumber("2", sUserWalletRecords.getRecharge_no());

                        //设置银行卡已支付
                        SUserBank userBank = new SUserBank();
                        userBank.setUserId(sUserWalletRecordsResult.getUser_id());
                        userBank.setModifyTime(new Date());
                        userBank.setHasPaySuccess(2);
                        userBankMapper.updateByUserId(userBank);

                        SUser resultUser = userMapper.selectUserInfoById(userId);
                        //发送短信验证码

//                        HashMap<String, String> hashMap = new HashMap<>();
//                        hashMap.put("mobile", resultUser.getMobile());
//                        hashMap.put("tpl_id", "92420");
//                        hashMap.put("key", MobileCodeServiceImpl.SMS_KEY);
//                        hashMap.put("tpl_value", "#name#=" + resultUser.getRealName() + "&#time#=" + DateUtil.formatDateTime() + "&#money#=" + value);
//                        ObjectResult objectResult2 = HttpClientUtil.verificationOfBankCard(MobileCodeServiceImpl.SMS_URL, hashMap);

                        return ObjectResult.build("1", "交易成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                    }


                } else {
                    return ObjectResult.build("0", "验签失败0x08");
                }

            } else {
                return ObjectResult.build("0", "不存在的充值记录");
            }

        } else {
            return objectResult;
        }
    }

    //绑卡
    @Override
      public  ObjectResult bindingBankNo(XMLBean xmlBean){

        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        if (resultUser == null){
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        if (resultUser.getCardNoAuth() == 1){
            return ObjectResult.build("0", "您已绑定身份证");
        }

        //查询身份证是否被绑定
        SUser user = this.userMapper.selectUserIdByIdAndCardNo(xmlBean.getCard_no());
        if (user != null) {
            return ObjectResult.build("0", "该身份证已被绑定");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank != null){
            return ObjectResult.build("0", "您已绑定银行卡");
        }

//        String requestReferenceID = P2PXmlUtils.getRequestReferenceID();
//        String data = "1.0" + "|" + "NN" + "|" + MCHNT_CD + "|" + requestReferenceID + "|" + xmlBean.getReal_name() + "|" + xmlBean.getCard_no() + "|" + KEY;
//        LOGGER.info("====签名明文===="+data);
//        String sign = p2PMessageUtils.getMD5(data);
//        LOGGER.info("====签名密文===="+sign);
//        if (sign == null || sign.equals("")) {
//            LOGGER.error("获取sign失败");
//            return ObjectResult.build("0", "服务器错误0x01,请重试");
//        }
//
//        //拼接报文
//        StringBuffer sb = new StringBuffer();
//        sb.append("<ORDER><VERSION>1.0</VERSION>");
//        sb.append("<TYPEID>NN</TYPEID>");
//        sb.append("<MCHNTCD>" + MCHNT_CD + "</MCHNTCD>");
//        sb.append("<MCHNTORDERID>" + requestReferenceID + "</MCHNTORDERID>");
//        sb.append("<NAME>" + xmlBean.getReal_name() + "</NAME>");
//        sb.append("<IDNO>" + xmlBean.getCard_no() + "</IDNO>");
//        sb.append("<REM1></REM1><REM2></REM2><REM3></REM3>");
//        sb.append("<SIGN>" + sign + "</SIGN></ORDER>");
//
//        //获取返回结果
//        ObjectResult result = p2PMessageUtils.getDecXml(P2P_SEND_MSG_URL + "checkInfo/checkIdentity.pay", sb.toString(), 1);

//        if (result.getData() != null && result.getCode().equals("1")) {
//            Map<String, String> xmlElementMap = (Map<String, String>) result.getData();
//            //身份证认证成功
//            if (xmlElementMap.get("MCHNTORDERID").equals(requestReferenceID)) {

                //验证银行卡
                //生成sign
                String bankRequestReferenceID = P2PXmlUtils.getRequestReferenceID();
                String bankData = MCHNT_CD + "|1.30|" + bankRequestReferenceID + "|" + xmlBean.getBank_no() + "|0|" + xmlBean.getCard_no() + "|" + KEY;
                LOGGER.info("====签名明文===="+bankData);
                String bankSign = p2PMessageUtils.getMD5(bankData);
                LOGGER.info("====签名密文===="+bankSign);
                if (bankSign == null || bankSign.equals("")) {
                    LOGGER.error("获取sign失败");
                    return ObjectResult.build("0", "服务器错误0x01,请重试");
                }

                //拼接报文
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("<FM>");
                stringBuffer.append("<MchntCd>" + MCHNT_CD + "</MchntCd>");
                stringBuffer.append("<Ono>" + xmlBean.getBank_no() + "</Ono>");
                stringBuffer.append("<Onm>" + xmlBean.getReal_name() + "</Onm>");
                stringBuffer.append("<OCerTp>0</OCerTp>");
                stringBuffer.append("<OCerNo>" + xmlBean.getCard_no() + "</OCerNo>");
                stringBuffer.append("<Mno>" + xmlBean.getMobile() + "</Mno>");
                stringBuffer.append("<Sign>" + bankSign + "</Sign>");
                stringBuffer.append("<Ver>1.30</Ver>");
                stringBuffer.append("<OSsn>" + bankRequestReferenceID + "</OSsn>");
                stringBuffer.append("</FM>");

                //获取返回结果
                ObjectResult bankResult = p2PMessageUtils.getDecXml(P2P_SEND_MSG_URL + "checkCard/checkCardDebit.pay", stringBuffer.toString(), 2);


                if (bankResult.getData() != null && bankResult.getCode().equals("1")) {

                    Map<String, String> bankXmlElementMap = (Map<String, String>) bankResult.getData();
                    //银行卡验证成功
                    if (bankXmlElementMap.get("OSsn").equals(bankRequestReferenceID) && bankXmlElementMap.get("CardNo").equals(xmlBean.getBank_no())
                            && bankXmlElementMap.get("MchntCd").equals(MCHNT_CD)) {

                        //更新数据库
                        resultUser.setRealNameAuth(1);
                        resultUser.setCardNoAuth(1);
                        resultUser.setCardNo(xmlBean.getCard_no());
                        resultUser.setRealName(xmlBean.getReal_name());
                        resultUser.setCardType(1);
                        userMapper.updateByPrimaryKeySelective(resultUser);

                        Long user_Id = resultUser.getId();
                        //更新数据库
                        SUserBank bank = new SUserBank();
                        bank.setUserId(user_Id);//用户id
                        bank.setBankName(bankXmlElementMap.get("Cnm"));//发卡银行名称
                        bank.setPayType("10");//默认是快捷支付（借记卡）
                        bank.setBankCode(bankXmlElementMap.get("InsCd"));//银行编号
                        bank.setIdType(1);//身份证或者是其他
                        bank.setMobile(xmlBean.getMobile());//卡的手机号
                        bank.setIdNo(xmlBean.getCard_no());//身份证号
                        bank.setAcctName(xmlBean.getReal_name());//该卡归属人姓名
                        bank.setPayChannel(Integer.valueOf(1));//支付渠道---连连支付
                        bank.setIsDeleted(Integer.valueOf(0));//默认是解绑状态等 银行绑定成功该变该值
                        bank.setBankCardNo(bankXmlElementMap.get("CardNo"));//银行卡号
                        bank.setHasPaySuccess(Integer.valueOf(1));//是否成功支付过---1未支付成功,2支付成功
                        bank.setAddTime(new Date());//添加日期
                        bank.setAddUserId(user_Id);//添加人
                        bank.setModifyTime(new Date());
                        bank.setModifyUserId(user_Id);
                        userBankMapper.insertSelective(bank);

                        return ObjectResult.build("1", "绑卡成功");

                    }else {
                        return ObjectResult.build("0", "验证银行卡失败" + bankXmlElementMap.get("RDesc"));
                    }

                }else {
                    return bankResult;
                }


//            }else {
//                return ObjectResult.build("0", "验证身份证失败" + xmlElementMap.get("RESPONSEMSG"));
//            }
//
//        }else {
//            return result;
//        }
    }



    //企业绑卡
    public ObjectResult enterpriseBindingBankNo(XMLBean xmlBean) {

        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        if (resultUser == null){
            return ObjectResult.build("0", "信息错误,请重试");
        }

        if (resultUser.getCardNoAuth() == 1){
            return ObjectResult.build("0", "您已绑定营业执照");
        }

        //查询身份证是否被绑定
        SUser user = this.userMapper.selectUserIdByIdAndCardNo(xmlBean.getCard_no());
        if (user != null) {
            return ObjectResult.build("0", "该营业执照被绑定");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank != null){
            return ObjectResult.build("0", "已绑定银行卡");
        }
                //更新数据库
                resultUser.setRealNameAuth(1);
                resultUser.setCardNoAuth(1);
                resultUser.setCardNo(xmlBean.getCard_no());
                resultUser.setRealName(xmlBean.getReal_name());
                resultUser.setCardType(1);
                userMapper.updateByPrimaryKeySelective(resultUser);

                Long user_Id = resultUser.getId();
                //更新数据库
                SUserBank bank = new SUserBank();
                bank.setUserId(user_Id);//用户id
                bank.setBankName(xmlBean.getBank_name());//发卡银行名称
                bank.setPayType("10");//默认是快捷支付（借记卡）
                bank.setBankCode(xmlBean.getBank_code());//银行编号
                bank.setIdType(1);//身份证或者是其他
                bank.setMobile(xmlBean.getMobile());//卡的手机号
                bank.setIdNo(xmlBean.getCard_no());//身份证号
                bank.setAcctName(xmlBean.getReal_name());//该卡归属人姓名
                bank.setPayChannel(Integer.valueOf(1));//支付渠道---连连支付
                bank.setIsDeleted(Integer.valueOf(0));//默认是解绑状态等 银行绑定成功该变该值
                bank.setBankCardNo(xmlBean.getBank_no());//银行卡号
                bank.setHasPaySuccess(Integer.valueOf(1));//是否成功支付过---1未支付成功,2支付成功
                bank.setAddTime(new Date());//添加日期
                bank.setAddUserId(user_Id);//添加人
                bank.setModifyTime(new Date());
                bank.setModifyUserId(user_Id);
                userBankMapper.insertSelective(bank);

                return ObjectResult.build("1", "绑卡成功");
        }

    @Test
    public void demo(){

        /**
         * 2018-01-05 16:10:49,421 [INFO] rongxue.service.utils.P2PMessageUtils - 发送的报
         文=========<ORDER><VERSION>1.0</VERSION><TYPEID>NN</TYPEID><MCHNTCD>0002900F0096
         235</MCHNTCD><MCHNTORDERID>4131801051610494</MCHNTORDERID><NAME>钟树梅</NAME><ID
         NO>430481199002047162</IDNO><REM1></REM1><REM2></REM2><REM3></REM3><SIGN>0076c63
         2e72bebde19dc6f8deb106f7e</SIGN></ORDER>
         */

        String data = "1.0|NN|0002900F0096235|7101801051609297|李杰|41142119940516775x|5old71wihg2tqjug9kkpxnhx9hiujoqj";

        /**
         * <ORDER><VERSION>1.0</VERSION><TYPEID>NN</TYPEID><MCHNTCD>0002900F0096
         235</MCHNTCD><MCHNTORDERID>0771801051602341</MCHNTORDERID><NAME>李杰</NAME><IDNO
         >41142119940516775x</IDNO><REM1></REM1><REM2></REM2><REM3></REM3><SIGN>844b21d30
         0e4df5f705e0f9da608e94e</SIGN></ORDER>
         */

        //String data = "1.0|NN|0002900F0096235|0771801051602341|李杰|41142119940516775x|5old71wihg2tqjug9kkpxnhx9hiujoqj";

        //String data = "1.0" + "|" + "NN" + "|"+MCHNT_CD+"|0771801051540070|秦秀标|440825196012174316|" + KEY;

        /*<ORDER><VERSION>1.0</VERSION><TYPEID>NN</TYPEID><MCHNTCD>0002900F0096
        235</MCHNTCD><MCHNTORDERID>0771801051540070</MCHNTORDERID><NAME>秦秀标</NAME><ID
        NO>440825196012174316</IDNO><REM1></REM1><REM2></REM2><REM3></REM3><SIGN>6e38886
        2584a288bef4082017fa4b1fc</SIGN></ORDER>*/

        //String data = "1.0" + "|" + "NN" + "|0002900F0096235|0771801051540070|秦秀标|440825196012174316|5old71wihg2tqjug9kkpxnhx9hiujoqj";
        //<ORDER><VERSION>1.0</VERSION>
        // <TYPEID>NN</TYPEID>
        // <MCHNTCD>0002900F0096235</MCHNTCD>
        // <MCHNTORDERID>5301801051522255</MCHNTORDERID>
        // <NAME>钟树梅</NAME><IDNO>430481199002047162</IDNO>
        // <REM1></REM1><REM2></REM2><REM3></REM3><SIGN>cceeff0e8e146ab4b28ba58bbecbbba4</SIGN></ORDER>

        String md5 = new P2PMessageUtils().getMD5(data);
        System.out.println(md5);
        System.out.println(md5.length());
        System.out.println("0076c632e72bebde19dc6f8deb106f7e".length());

    }
}
